﻿using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using iemtm.WeChat.Core;
using iemtm.WeChat.Core.Managers;
using Mapster;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;

namespace iemtm.WeChat.Application.UserCenter
{
    /// <summary>
    /// 授权服务
    /// </summary>

    public class AuthorizeService : IAuthorizeService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
 
        private readonly IUserManager _userManager;

        public AuthorizeService(IUserManager userManager
          )
        {
            _userManager = userManager;
           
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public  async Task<LoginOutput> LoginAsync([FromServices] IHttpContextAccessor httpContextAccessor, [Required] LoginInput input)
        {

            var loginUser=await _userManager.CheckUserAsync(input.UserCode, input.UserPwd);
            
            if (loginUser != null)
            {
                // 映射结果
               var  output = loginUser.Adapt<LoginOutput>();
                // 生成 token
                var accessToken = output.AccessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                {
                    { "UserId",loginUser.Id },
                    { "Account",loginUser.UserCode }
                });

                

                // 生成 刷新token
                var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken,10);//// 第二个参数是刷新 token 的有效期，默认三十天
                // 设置 Swagger 自动登录
                httpContextAccessor.SigninToSwagger(accessToken);
                // 设置刷新 token
                httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
                httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;

                return output;
            }
            
            return null;
            
        }
    }
}
